package com.yonyou.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

import javax.crypto.Cipher;
import java.io.*;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiash
 * @since 2021/11/18
 */
public class RsaUtil {
    public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVM/ArTS3umBFclsDG3LUL4+CjHqOyZ3A9yZ6rJ5949fH7w5dYuap2m6TMboZGyMi8VKf+W8SRwQe0zOdisMy5sgfHfBPsvE64MWukUYe8BezXbyEvZ6i9VbDJ8eSk0+UTt7PExYcRijMJ6t2fHx1KWhwWiuhwsk6f4c0z1v9KSQIDAQAB";

    public static void main(String[] args) {
        // map里是真正的参数
        Map<String,String> params = new HashMap<>();
        params.put("accessToken", "ssssssss");
        params.put("openId", "4444");
        params.put("randCode", "NFFJYMJ5RTG5Y7TXESVT");
        String text = JSONObject.toJSONString(params);
//        System.out.println(text);
        String ans = encrypt(text);
        // ans是加密后的值
        System.out.println(URLEncoder.encode(ans));
//        String result = YhtSimpleRsaUtils.decrypt(ans, "");
//        String result = YhtSimpleRsaUtils.decrypt(ans, "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALr7NfO854TYS0r4/D3o9GbKLYocIgQpA9QquXlogAmFWWwzE9Y6FVqGUFdVzhcMMtJkRQ23RPcY9xi0aYtnNSs2sWdpNkBPKGqX2I4aCQRedZsMyRRS8RWl7wfp7u2h1JVScx351YI9kcJPoIABoM3LvoednMvF8iY+v7QvX6nDAgMBAAECgYAFwBcLLWqTV9GM9zZOsxzdEmevISlcpmRDQKMenDufz1WOMc3w3y1r8MiEvxNM+yeO9911zAaXcNGclWPPkTd91LNOGZo5up7p0/IRhdqpbpsRYQG4TdTtH3cWmqIQSidZIObb8umUxFTyl9wfuOUd9qGgCLTsdAruCD5cAjc00QJBAPL21J+hNpjhHgQ9FL+/aofY6GDjCRhdmHH/AiS3VmgjOs5YINRNQ3KS5dWBo9P7lVCBaK4q/0XOqnM7/6PAUrECQQDFA3E0G2DdQRT2L0K+7IaPvMV110VEtUfvATlwCCkC/rvXfiS9sXBnUxUGACzk8wki858NTG+Xx0K+MQyvSVizAkA0S4B0Y2S2/y1QyDzhELhDSSKrR/K7NdoMH1E8yeFlRL/xjfJy/7ZWwNuLWv4CMJJw44m+gy6yvcreRrm9azXhAkEAiZBivjCTzUpBWbkcUPYU606zTho3Wsd95+wh8BEymc3G2axR+UZppywDFQKQVnlBGu+jUoTZstBG0Uisg8SiMwJBAJEVBjb8/zf1BXLkJuKsabWR/w04f4rg+UMm0nergKEnGUtpJPQSbHt9sptZqBcRQDOqxh/Mr5WfXVer4o+eUsg=");
//        System.out.println(result);

    }

    public static String encrypt(String data) {
        try {
            return encryptBASE64(encryptByPublicKey(data, publicKey));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String encryptBASE64(byte[] bytes) {
        return new String(Base64.encodeBase64(bytes));
    }
    public static byte[] encryptByPublicKey(String data, String key) throws Exception {
        // 对公钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] inputArray = data.getBytes();
        int inputLength = inputArray.length;
        // 最大加密字节数，超出最大字节数需要分组加密
        int MAX_ENCRYPT_BLOCK = 117;
        // 标识
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache = {};
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                offSet += MAX_ENCRYPT_BLOCK;
            } else {
                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                offSet = inputLength;
            }
            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
        }
        return resultBytes;
    }

    public static byte[] decryptBASE64(String key) {
        return Base64.decodeBase64(key.getBytes());
    }

}
